package com.jml.springmvc.手写008.servlet;


import com.jml.springmvc.手写008.handler.HandlerExecutionChain;
import com.jml.springmvc.手写008.handler.HandlerMethod;
import com.jml.springmvc.手写008.servlet.web.RequestMappingHandlerMapping;
import com.jml.springmvc.手写008.view.ModelAndView;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:jml
 * @date: 2019/10/11 14:54
 * @description：
 */
public class DispatcherServlet extends FrameworkServlet {
	
	private RequestMappingHandlerMapping requestMappingHandlerMapping;
	
	public DispatcherServlet() {
		requestMappingHandlerMapping = new RequestMappingHandlerMapping();
	}
	
	@Override
	protected void onRefresh() {
		initStrategies();
	}
	
	private void initStrategies() {//url和对应方法的map初始化
		System.out.println("------------------容器开始初始化！！------------------");
		requestMappingHandlerMapping.initHandlerMappings();
	}
	
	@Override
	protected void doService(HttpServletRequest req, HttpServletResponse resp) {
		doDispatch(req, resp);
	}
	
	private void doDispatch(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// 1.处理请求url
			String requestURI = req.getRequestURI();
			// 2.根据url查找对应的Handler
			HandlerExecutionChain handler = getHandler(requestURI);
			if (handler == null) {
				noHandlerFound(req, resp);
				return;
			}
			// 3.使用java的反射机制执行请求方法 返回对应的modelAndView
			ModelAndView modelAndView = handler.handler();
			// 4.开始渲染视图层
			render(modelAndView, req, resp);
		} catch (Exception e) {
		
		}
	}
	
	private HandlerExecutionChain getHandler(String url) {
		HandlerMethod handlerMethod = requestMappingHandlerMapping.getHandlerMethod(url);
		if (handlerMethod == null) {
			return null;
		}
		HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain(handlerMethod);
		return handlerExecutionChain;
	}
	
	public void render(ModelAndView modelAndView, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String viewName = modelAndView.getViewName();
		req.getRequestDispatcher("/WEB-INF/view/" + viewName + ".jsp").forward(req, resp);
	}
	
	
	
	protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
		throw new Exception("没有查找到对应的请求");
	}
	
	public static void main(String[] args) throws ServletException {
		DispatcherServlet dispatcherServlet = new DispatcherServlet();
		dispatcherServlet.init();
	}
}
